// pages/partnercenter/orderpay/orderpay.js
var app = getApp();
var payflagnum = 0, sendflag = true, bindflag = false;
var shihan = require('../../../common/fetch')
var config = require('../../../common/config')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    agreeflag: false,
    address_info: '省、市、县'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    var goods = JSON.parse(options.goods);
    this.setData({
      childid: goods.sh_child_id,
      productid: goods.sh_product_id,
      productname: goods.sh_product_name,
      productprice: goods.sh_price,
      partnerid: goods.sh_partner_id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.selectAddress = this.selectComponent("#selectAddress");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },

  showPopup: function () {
    this.selectAddress._showPopup();
  },

  disabledArea: function (e) {
    this.setData({
      disabled_area: e.detail == 1 ? true : false
    })
  },
  changeAddress: function (e) {
    //e.detail 自定义组件触发事件时提供的detail对象
    this.setData({
      provinceName: e.detail.provinceName,
      province_id: e.detail.province_id,
      cityName: e.detail.cityName,
      city_id: e.detail.city_id,
      region_id: e.detail.region_id,
      regionName: e.detail.regionName,
      address_info: e.detail.address
    })
  },

  formSubmit: function (e) {
    // 收货人
    var realname = e.detail.value.realname;
    // 联系电话
    var usemobile = e.detail.value.mobile;
    // detail
    var detail = e.detail.value.detail;

    // 表单验证
    if (realname == '') {
      shihan.showToast.call(this, '请填写收件人')
      return;
    }
    if (!usemobile) {
      shihan.showToast.call(this, '请填写正确手机号码')
      return;
    }
    if (this.data.address_info == '省、市、县') {
      shihan.showToast.call(this, '请输入所在地区')
      return;
    }
    if (detail == '') {
      shihan.showToast.call(this, '详情地址不能为空')
      return;
    }
    if (!this.data.agreeflag) {
      shihan.showToast.call(this, '请同意并遵守合伙人协议')
      return;
    }
    this.orderpay(realname, usemobile, detail, e);
  },
  selectagree: function () {
    this.setData({
      agreeflag: !this.data.agreeflag
    })
  },
  lookagree: function () {
    wx.navigateTo({
      url: '/pages/strategyinfo/strategyinfo?share=0&nologin=1&url=' + encodeURIComponent(config.commonurl + 'h5/partner/agreement.html')
    })
  },
  orderpay: function (realname, usemobile, detail, ae) {
    payflagnum++
    var data = {}, that = this;
    data['address'] = detail; //收货地址
    data['child_id'] = that.data.childid; //子商品id 22964
    data['full_name'] = realname; //收货人
    data['mobile'] = usemobile; //电话
    data['partner_id'] = that.data.partnerid; //推荐合伙人id	
    data['product_id'] = that.data.productid; //主商品id  '1145'

    data['province'] = that.data.provinceName; //省份
    data['province_id'] = that.data.province_id; //省份id
    data['city'] = that.data.cityName; //城市
    data['city_id'] = that.data.city_id; //城市id
    data['area'] = that.data.regionName; //地区
    data['area_id'] = that.data.region_id; //地区id

    if (payflagnum == 1) {
      shihan.sendRequest(config.partner_generate_order, 'POST', data)
        .then(function (response) {
          console.log(response);
          if (response.data.code == 0) {
            payflagnum++
            that.setData({
              payment_status: response.data.data.sh_payment_status, //"unpaid" 红包不足以支付
              trade_no: response.data.data.sh_trade_no // 交易单号'T2017072519130313498'
            })
            if (response.data.data.sh_payment_status == 'unpaid') {
              wx.login({
                success: function (res) {
                  shihan.sendRequest(config.get_wx_perpay, 'POST', {
                    trade_no: that.data.trade_no,
                    code: res.code
                  })
                    .then(function (response) {
                      if (response.data.code == 0) {
                        payflagnum = 0
                        var prepayid = response.data.data.sh_package;
                        wx.requestPayment({
                          "appId": response.data.data.sh_appid,
                          'timeStamp': new String(response.data.data.sh_timestamp),
                          'nonceStr': response.data.data.sh_noncestr,
                          'package': response.data.data.sh_package,
                          'signType': 'MD5',
                          'paySign': response.data.data.sh_sign,
                          'success': function (res) {
                            app.submissionForm(prepayid.split('=')[1], '3', '4')
                            app.data.partnerflag = 1
                            app.data.setupdownloadimgflag = 0
                            wx.switchTab({
                              url: '/pages/mine/mine',
                            })
                          },
                          'fail': function (res) {
                            app.submissionForm(ae.detail.formId, '1', '3')
                            wx.redirectTo({
                              url: '/pages/myorder/myorder?orderindex=1&partnerbuy=1',
                            })
                          }
                        })
                      } else {
                        payflagnum = 0;
                        shihan.showToast.call(that, response.data.msg);
                      }
                    }, function (error) {
                      console.log(error);
                    });
                }
              })
            } else {
              wx.redirectTo({
                url: '/pages/paysuccess/paysuccess?bupiao=1&tradeno=' + that.data.trade_no,
              })
            }
          } else {
            payflagnum = 0;
            shihan.showToast.call(that, response.data.msg);
          }
        }, function (error) {
          payflagnum = 0
          console.log(error);
        });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  }
})